<?php
class Dijkstra_Map{
	
	private $nodes = array();
	private $links = array();
	
	private $map = array();
	
	private $nodeIndex = array();
	
	public function addNode(Dijkstra_Node $node){
		if( $this->getNode($node->getName()) === null ){
			$this->nodes[] = $node;
			
			$this->nodeIndex[$node->getName()] = $node;

			return $node;
		}else{
			return $this->nodeIndex[$node->getName()];
		}
	}
	
	public function addLink(Dijkstra_Link $link){
		$x = array_search($link->getNodeA(), $this->nodes);
		$y = array_search($link->getNodeB(), $this->nodes);
			
		if($x === false || $y === false){
			return null;
		}
		
		if( isset($this->map[$x][$y]) || isset($this->map[$y][$x]) )
			return $this->map[$x][$y];
		
		$this->link[] = $link;
			
		$this->map[$x][$y] = $link;
		$this->map[$y][$x] = $link;
		
		return $link;
	}
	
	public function getNode($nodeName){
		if( key_exists($nodeName, $this->nodeIndex))
			return $this->nodeIndex[$nodeName];
		return null;
	}
	
	public function getNodeIndex(Dijkstra_Node $node){
		return array_search($node, $this->nodes);
	}
	
	public function getNodeByIndex($index){
		return $this->nodes[$index];
	}
	
	public function printMap(){
		$placeholder = ' %' . strlen("20000") .'d';
		
		$foo = '';
		for($i=0,$im=count($this->map); $i<$im; $i++) {
			for ($k=0,$m=$im; $k<$m; $k++) {
				$foo.= sprintf($placeholder, isset($this->map[$i][$k]) ? $this->map[$i][$k]->getWeight() : -1);
			}
			$foo.= "\n";
		}
		return $foo;
	}
	
	public function getMap(){
		return $this->map;
	}
}